package wangwenjun.phase3.executor.completablefuture.demo02;

import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ChangLiang
 * @date 2020/10/11
 */
public class ParallelDataLoader extends DataLoader {

    @Override
    protected void doLoad() {
        // 并行计算
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        CompletionService completionService = new ExecutorCompletionService(executorService);
        completionService.submit(super::loadConfigurations, null);
        completionService.submit(super::loadUsers, null);
        completionService.submit(super::loadOrders, null);
        int count = 0;
        while (count < 3) {
            // 等待三个任务完成 poll是不阻塞的，如果使用future.get 就阻塞了
            if (completionService.poll() != null) {
                count++;
            }
        }
        // 线程关闭 程序才能执行结束
        executorService.shutdown();
    }

    public static void main(String[] args) {
        new ParallelDataLoader().load();
    }
}
